<?php
// +----------------------------------------------------------------------
// | MC PHP[基于ThinkPHP6.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2020-2023 http://www.mingchangruanjian.com
// +----------------------------------------------------------------------
// | Author jokerfei [ jokerfei377@gmail.com ]
// +----------------------------------------------------------------------
// | 铭畅软件 技术部 出品
// +----------------------------------------------------------------------
namespace app\common\model;

use think\facade\Cache;

/**
 * 用于保存各个API的字段规则
 * @package app\common\model
 */
class Apilist extends BaseModel
{

    protected $name = 'system_api_list';

    protected $autoWriteTimestamp = true;

    //只读字段,一旦写入，就无法更改。
    protected $readonly = ['hash'];

    public function getMethodTurnAttr($value, $data)
    {    //请求方式 method 字段 [获取器]
        $turnArr = [0 => '不限', 1 => 'POST', 2 => 'GET'];
        return $turnArr[$data['method']];
    }

    public function getNeedLoginTurnAttr($value, $data)
    {    //是否需要认证用户token needLogin 字段 [获取器]
        $turnArr = [0 => '不验证登录', 1 => '验证登录'];
        return $turnArr[$data['needlogin']];
    }

    public function getIsTestTurnAttr($value, $data)
    {    //是否是测试模式 isTest 字段 [获取器]
        $turnArr = [-1 => 'MOCK数据', 0 => '测试模式', 1 => '生产模式'];
        return $turnArr[$data['istest']];
    }

    public function getStatusTurnAttr($value, $data)
    {    //接口状态 Status 字段 [获取器]
        $turnArr = [0 => '接口被禁用', 1 => '正常访问'];
        return $turnArr[$data['status']];
    }

    /**
     * 获取缓存API INFO
     * @Author jokerfei [ jokerfei377@gmail.com ]
     * @param string $hash 接口HASH
     * @return array|null
     */
    public static function getCacheInfo(string $hash)
    {
        static $info = null;
        $apiInfoArr = null;
        // 生产模式，获取缓存数据
        if (!config('cache.develop_mode')) {
            $apiInfoArr = cache('apiInfo_' . $hash);
            if (empty($apiInfoArr) && $info === null) {
                $apiInfo = (new Apilist)->where([['hash', '=', $hash], ['status', '=', 1]])->find();
                if ($apiInfo) {
                    $apiInfoArr = $apiInfo->toArray();
                    Cache::tag('api')->set('apiInfo_' . $hash, $apiInfoArr, 7200); //接口信息
                    $info = 1;
                }
                else {
                    return null;
                }
            }
        }
        else {
            // 开发模式，直接获取最新数据
            $apiInfo = (new Apilist)->where([['hash', '=', $hash], ['status', '=', 1]])->find();
            if ($apiInfo) {
                $apiInfoArr = $apiInfo->toArray();
            }
        }
        return $apiInfoArr;
    }
}